<template>
    <div ref="mapChart" style="width: 100%; height: 100%;"></div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref } from "vue";
import * as echarts from "echarts";
import hebeiGeoJson from "../assets/map/bjtjhbGeoJson.json";
import { projectLocations } from "@/api/workorder/projectInfo/mockData";
import Cookies from "js-cookie";
import { useRouter } from "vue-router";

export default defineComponent({
name: "HebeiMap",
setup() {
    const mapChart = ref<HTMLDivElement | null>(null);
    const chart = ref<echarts.ECharts | null>(null);
    const router = useRouter();

    const initMap = () => {
        if (!mapChart.value) return;

        try {
            // 确保 GeoJSON 数据格式正确
            if (!hebeiGeoJson || !hebeiGeoJson.features) {
                console.error("Invalid GeoJSON data");
                return;
            }

            // 注册地图
            echarts.registerMap("hebei", hebeiGeoJson as any);
            
            // 初始化图表
            chart.value = echarts.init(mapChart.value);

            const option = {
                backgroundColor: "transparent",
                geo: {
                    show: false, // 隐藏 geo 组件，因为我们使用 map series 来显示地图
                    map: "hebei",
                },
                series: [
                    {
                        name: "河北省项目",
                        type: "map",
                        map: "hebei",
                        roam: true,
                        zoom: 1.2,
                        center: [116.481499, 39.990475],
                        label: {
                            show: true,
                            color: "#333",
                        },
                        itemStyle: {
                            areaColor: "#34bcf3",
                            borderColor: "#111",
                        },
                        emphasis: {
                            label: {
                                show: true,
                                color: "#fff",
                            },
                            itemStyle: {
                                areaColor: "#77d6f9",
                            },
                        },
                        // 添加标记点数据
                        markPoint: {
                            symbol: 'circle',
                            symbolSize: 12,
                            effect: {
                                show: true,
                                type: 'ripple',
                                brushType: 'stroke',
                                period: 3,
                                scale: 2.5
                            },
                            label: {
                                show: true,
                                position: "right",
                                distance: 10,
                                formatter: function(params) {
                                    const project = projectLocations.find(p => p.name === params.name);
                                    if (!project) return '';
                                    return [
                                        `{title|${params.name}}`,
                                        `{info|${project.description}}`,
                                        `{status|${project.status}}`
                                    ].join('\n');
                                },
                                rich: {
                                    title: {
                                        color: '#333',
                                        fontSize: 14,
                                        fontWeight: 'bold',
                                        padding: [0, 0, 5, 0],
                                    },
                                    info: {
                                        color: '#666',
                                        fontSize: 12,
                                        width: 150,
                                        overflow: 'truncate'
                                    },
                                    status: {
                                        color: '#0066cc',
                                        fontSize: 12,
                                        padding: [5, 0, 0, 0]
                                    }
                                },
                                backgroundColor: 'rgba(255,255,255,0.9)',
                                padding: [5, 10],
                                borderRadius: 4,
                            },
                            data: projectLocations.map(item => ({
                                name: item.name,
                                value: item.description,
                                coord: [item.longitude, item.latitude],
                                itemStyle: {
                                    color: item.type === "商业" ? "#ff0" : "#0ff"
                                },
                                activeIndex: item.activeIndex
                            }))
                        }
                    }
                ],
                tooltip: {
                    show: false
                },
            };

            chart.value.setOption(option);

            // 添加点击事件
            chart.value.on("click", (params: any) => {
                // 检查是否点击了标记点
                if (params.componentType === 'markPoint') {
                    // 从点击的数据中获取项目名称
                    const clickedName = params.data?.name;
                    const project = projectLocations.find((p) => p.name === clickedName);
                    if (project) {
                        // 根据activeIndex确定跳转路径
                        const paramsUrl = project.activeIndex === 0 ? '/ruleInfo' : 
                                        project.activeIndex === 2 ? '/oss' : 
                                        '/projectInfoPage';
                        
                        // 使用 router.push 进行跳转
                        router.push({ 
                            path: paramsUrl,
                            query: {
                                projectId: project.id,
                                projectName: project.name
                            }
                        });
                        
                        // 存储项目信息到 Cookies
                        Cookies.set("projectId", project.id);
                        Cookies.set("projectName", project.name);
                        Cookies.set("displayType", "workorder");
                    }
                }
            });
        } catch (error) {
            console.error("Error initializing map:", error);
        }
    };

    // 监听窗口大小变化
    const handleResize = () => {
        chart.value?.resize();
    };

    onMounted(() => {
        // 确保在组件挂载后再初始化地图
        setTimeout(() => {
            initMap();
        }, 0);
        window.addEventListener("resize", handleResize);
    });

    onUnmounted(() => {
        window.removeEventListener("resize", handleResize);
        chart.value?.dispose();
    });

    return {
        mapChart,
    };
},
});
</script>

<style scoped>
/* 样式可以根据需要调整 */
</style>
